package com.yx.fx.webApi.job;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yx.fx.webApi.mapper.TEnterpriseMapper;
import com.yx.fx.webApi.entity.*;
import com.yx.fx.webApi.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Component
public class QuartzJobs {
    //1.    获取企业信息
    String baseUrl1 = "http://47.97.201.177:8082/data.ws/api/data/getCompanyInfos?";

    //2.	获取企业信息列表
    String baseUrl2 = "http://47.97.201.177:8082/data.ws/api/data/getCompanyInfosList?";

    //3.	获取变更企业信息列表
    String baseUrl3 = "http://47.97.201.177:8082/data.ws/api/data/getChangedCompanyInfosList?";

    //4.	查询新注册企业最新成立日期
    String baseUrl4 = "http://47.97.201.177:8082/data.ws/api/data/getCompanyLatestStartDate";
    //一天的毫秒数
    long daySpan = 24 * 60 * 60 * 1000;

    @Resource
    private TEnterpriseMapper tEnterpriseMapper;

    @Resource
    private TEnterpriseService tEnterpriseService;

    @Resource
    private TAddressService tAddressService;

    @Resource
    private TEnterpriseInvestmentService tEnterpriseInvestmentService;

    @Resource
    private TReportDetailsService tReportDetailsService;

    @Resource
    private TTelephonesService tTelephonesService;

    @Resource
    private TBranchesService tBranchesService;

    @Resource
    private TEmailsService tEmailsService;

    @Resource
    private TPartnersService tPartnersService;

    @Resource
    private TWebsitesService tWebsitesService;

    @Autowired
    private TEmployeesService tEmployeesService;

    @Resource
    private TSocialSecurityService tSocialSecurityService;

    @Resource
    private TLastIndustryService tLastIndustryService;

    @Resource
    private TChangeRecordsService tChangeRecordsService;


    /**
     * 获取本地最新注册日期
     *
     * @return 返回最新注册日期+1
     */
    private String getLastDate() {
        String lastDate = tEnterpriseMapper.getLastDate().getStartDate();
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        /**
         * 加一天
         */
        try {
            Date startDate = dateFormat.parse(lastDate);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(startDate);
            calendar.add(Calendar.DAY_OF_MONTH, 1);//加一天
            log.info("增加一天之后：" + dateFormat.format(calendar.getTime()));
            return dateFormat.format(calendar.getTime());
        } catch (ParseException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    /**
     * 定时器
     * spring定时任务
     */
    @Scheduled(cron = "0 34 23 ? * * ")
    public void getCompanyInfosList() {
        log.info("定时器执行");
        String getCompanyLatestStartDate = TEnterpriseThirdApi.getResult(baseUrl4, null);
        JSONObject jsonObject = JSON.parseObject(getCompanyLatestStartDate);
        JSONObject data = jsonObject.getJSONObject("data");
        String startDateEnd = data.getString("startDate");
        if (StringUtils.isNotBlank(startDateEnd)) {
            String startDateStart = getLastDate();
            int result = startDateEnd.compareTo(startDateStart);
            if (result > 0) {
                Map<String, String> params = new HashMap<>();
                params.put("startDateStart", startDateStart);
                params.put("startDateEnd", startDateEnd);
                log.info("新企业入库开始");
                String getCompanyInfosList = TEnterpriseThirdApi.getResult(baseUrl2, params);
                JSONObject companyList = JSON.parseObject(getCompanyInfosList);
                this.doAdd(companyList);
                log.info("新企业入库结束");
                log.info("新企业变更入库开始");
                String getChangedCompanyInfosList = TEnterpriseThirdApi.getResult(baseUrl3, params);
                JSONObject changedCompanyList = JSON.parseObject(getChangedCompanyInfosList);
                this.doAdd(changedCompanyList);
                log.info("新企业变更入库结束");
            }
            log.info("定时任务执行结束");
        }
    }

    private void doAdd(JSONObject jsonObject){
        JSONArray record = jsonObject.getJSONArray("data");
        if (record.size() > 0) {
            for (int i = 0; i < record.size(); i++) {
                //行记录
                JSONObject line = JSON.parseObject(record.get(i).toString());
                JSONArray address = line.getJSONArray("address");
                JSONArray enterpriseInvestment = line.getJSONArray("enterpriseInvestment");
                JSONArray reportDetails = line.getJSONArray("reportDetails");
                JSONArray telephones = line.getJSONArray("telephones");
                JSONArray branches = line.getJSONArray("branches");
                JSONArray emails = line.getJSONArray("emails");
                JSONArray partners = line.getJSONArray("partners");
                JSONArray websites = line.getJSONArray("websites");
                JSONArray employees = line.getJSONArray("employees");
                JSONArray socialSecurity = line.getJSONArray("socialSecurity");
                JSONArray lastIndustry = line.getJSONArray("lastIndustry");
                JSONArray changeRecords = line.getJSONArray("changeRecords");
                JSONObject enterprise = line.getJSONObject("enterprise");
                if (address.size() > 0) {
                    List<TAddress> addressList = address.toJavaList(TAddress.class);
                    tAddressService.saveOrUpdateBatch(addressList);
                }
                if (enterpriseInvestment.size() > 0) {
                    List<TEnterpriseInvestment> enterpriseInvestmentList = enterpriseInvestment.toJavaList(TEnterpriseInvestment.class);
                    tEnterpriseInvestmentService.saveOrUpdateBatch(enterpriseInvestmentList);
                }
                if (reportDetails.size() > 0) {
                    List<TReportDetails> reportDetailsList = reportDetails.toJavaList(TReportDetails.class);
                    tReportDetailsService.saveOrUpdateBatch(reportDetailsList);
                }
                if (telephones.size() > 0) {
                    List<TTelephones> telephonesList = telephones.toJavaList(TTelephones.class);
                    tTelephonesService.saveOrUpdateBatch(telephonesList);
                }
                if (branches.size() > 0) {
                    List<TBranches> branchesList = branches.toJavaList(TBranches.class);
                    tBranchesService.saveOrUpdateBatch(branchesList);
                }
                if (emails.size() > 0) {
                    List<TEmails> emailsList = emails.toJavaList(TEmails.class);
                    tEmailsService.saveOrUpdateBatch(emailsList);
                }
                if (partners.size() > 0) {
                    List<TPartners> partnersList = partners.toJavaList(TPartners.class);
                    tPartnersService.saveOrUpdateBatch(partnersList);
                }
                if (websites.size() > 0) {
                    List<TWebsites> websitesList = websites.toJavaList(TWebsites.class);
                    tWebsitesService.saveOrUpdateBatch(websitesList);
                }
                if (employees.size() > 0) {
                    List<TEmployees> employeesList = employees.toJavaList(TEmployees.class);
                    tEmployeesService.saveOrUpdateBatch(employeesList);
                }
                if (socialSecurity.size() > 0) {
                    List<TSocialSecurity> socialSecurityList = socialSecurity.toJavaList(TSocialSecurity.class);
                    tSocialSecurityService.saveOrUpdateBatch(socialSecurityList);
                }
                if (lastIndustry.size() > 0) {
                    List<TLastIndustry> lastIndustryList = lastIndustry.toJavaList(TLastIndustry.class);
                    tLastIndustryService.saveOrUpdateBatch(lastIndustryList);
                }
                if (changeRecords.size() > 0) {
                    List<TChangeRecords> changeRecordsList = changeRecords.toJavaList(TChangeRecords.class);
                    tChangeRecordsService.saveOrUpdateBatch(changeRecordsList);
                }
                if (!enterprise.isEmpty()) {
                    TEnterprise tEnterprise = enterprise.toJavaObject(TEnterprise.class);
                    tEnterpriseService.saveOrUpdate(tEnterprise);
                }
            }
        }
    }
}
